<template>
  <div class="calculate-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form layout="inline" :model="filterForm">
        <a-form-item label="日期范围">
          <a-range-picker
            v-model="filterForm.dateRange"
            format="YYYY-MM-DD"
            :placeholder="['开始日期', '结束日期']"
          />
        </a-form-item>
        <a-form-item label="项目组">
          <a-select
            v-model="filterForm.project_group_id"
            placeholder="请选择项目组"
            allowClear
            style="width: 200px"
          >
            <a-select-option 
              v-for="item in projectGroups" 
              :key="item.project_group_id" 
              :value="item.project_group_id"
            >
              {{ item.project_group_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="部门">
          <a-select
            v-model="filterForm.department_id"
            placeholder="请选择部门"
            allowClear
            style="width: 200px"
          >
            <a-select-option 
              v-for="item in departments" 
              :key="item.department_id" 
              :value="item.department_id"
            >
              {{ item.department_name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="审核状态">
          <a-select
            v-model="filterForm.approved_status"
            placeholder="请选择状态"
            allowClear
            style="width: 120px"
          >
            <a-select-option :value="0">待审核</a-select-option>
            <a-select-option :value="1">已审核</a-select-option>
            <a-select-option :value="2">未采用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否发布">
          <a-select
            v-model="filterForm.has_platform_submit_date"
            placeholder="请选择是否发布"
            allowClear
            style="width: 120px"
          >
            <a-select-option :value="0">全部</a-select-option>
            <a-select-option :value="1">已发布</a-select-option>
            <a-select-option :value="2">未发布</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="人员姓名">
          <a-input
            v-model="filterForm.person_name"
            placeholder="请输入人员姓名"
            allowClear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 投稿明细表格 -->
    <div class="table-area">
      <div class="table-header">
        <div class="title">
          <span class="icon"></span>
          <span>投稿明细</span>
        </div>
        <a-button type="primary" @click="exportDetail">
          <a-icon type="download" />导出Excel
        </a-button>
      </div>
      <vxe-table
        ref="xTable"
        :data="tableData"
        :loading="loading"
        :auto-resize="true"
        :max-height="600"
        border
        stripe
        resizable
        show-overflow="tooltip"
      >
        <vxe-column field="contribution_id" title="ID" width="60" />
        <vxe-column field="title" title="作品名" min-width="360" show-overflow="tooltip" />
        <vxe-column field="author1_name" title="作者1" width="160">
          <template v-slot="{ row }">
            {{ row.author1_name }} ({{ row.author1_department_name }})
          </template>
        </vxe-column>
        <vxe-column field="author2_name" title="作者2" width="160">
          <template v-slot="{ row }">
            <template v-if="row.author2_name">
              {{ row.author2_name }} ({{ row.author2_department_name }})
            </template>
          </template>
        </vxe-column>
        <vxe-column field="author3_name" title="作者3" width="160">
          <template v-slot="{ row }">
            <template v-if="row.author3_name">
              {{ row.author3_name }} ({{ row.author3_department_name }})
            </template>
          </template>
        </vxe-column>
        <vxe-column field="project_group_name" title="项目组" width="120" />
        <vxe-column field="approved_status" title="审核状态" width="100">
          <template v-slot="{ row }">
            <a-tag :color="getStatusColor(row.approved_status)">
              {{ getStatusText(row.approved_status) }}
            </a-tag>
          </template>
        </vxe-column>
        <vxe-column field="approved_person_name" title="审核人" width="100" />
        <vxe-column field="score" title="总分" width="80" />
        <vxe-column field="scoring_person_name" title="打分人" width="100" />
        <vxe-column field="author1_score" title="作者1得分" width="100" />
        <vxe-column field="author2_score" title="作者2得分" width="100" />
        <vxe-column field="author3_score" title="作者3得分" width="100" />
        <vxe-column field="extra_score" title="额外得分" width="100" />
        <vxe-column field="tiktok_likes" title="抖音点赞数" width="120" />
        <vxe-column field="channels_views" title="视频号播放量" width="120" />
        <vxe-column field="channels_likes" title="视频号点赞数" width="120" />
        <vxe-column field="submission_date" title="提交时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.submission_date) }}
          </template>
        </vxe-column>
        <vxe-column field="platform_submit_date" title="发布时间" width="160">
          <template v-slot="{ row }">
            {{ formatDate(row.platform_submit_date) }}
          </template>
        </vxe-column>
        <vxe-column field="remarks" title="备注" min-width="150" show-overflow="tooltip" />

        <template #empty>
          <span style="color: #666">暂无数据</span>
        </template>
      </vxe-table>
    </div>

    <!-- 个人统计表格 -->
    <div class="table-area">
      <div class="table-header">
        <div class="title">
          <span class="icon"></span>
          <span>个人统计</span>
        </div>
        <a-button type="primary" @click="exportStats">
          <a-icon type="download" />导出Excel
        </a-button>
      </div>
      <vxe-table
        ref="statsTable"
        :data="statsData"
        :loading="statsLoading"
        :auto-resize="true"
        border
        stripe
        resizable
        show-overflow="tooltip"
      >
        <vxe-column field="person_name" title="姓名" />
        <vxe-column field="department_name" title="部门"  />
        <vxe-column title="作者1" align="center">
          <vxe-column field="author1.count" title="投稿数" />
          <vxe-column field="author1.score" title="得分"/>
        </vxe-column>
        <vxe-column title="作者2" align="center">
          <vxe-column field="author2.count" title="投稿数" />
          <vxe-column field="author2.score" title="得分"/>
        </vxe-column>
        <vxe-column title="作者3" align="center">
          <vxe-column field="author3.count" title="投稿数" />
          <vxe-column field="author3.score" title="得分" />
        </vxe-column>
        <vxe-column title="合计" align="center">
          <vxe-column field="total.count" title="投稿数" />
          <vxe-column field="total.score" title="总得分" />
        </vxe-column>

        <template #empty>
          <span style="color: #666">暂无数据</span>
        </template>
      </vxe-table>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import XLSX from 'xlsx'
import { 
  apiProjectGroupList, 
  apiDepartmentList, 
  apiContributionGetStatsList,
  apiPersonGetAllContributionStats
} from '@/api/featch'

export default {
  name: 'Calculate',
  data() {
    return {
      loading: false,
      statsLoading: false,
      filterForm: {
        dateRange: [],
        project_group_id: undefined,
        department_id: undefined,
        person_name: '',
        approved_status: undefined,
        has_platform_submit_date: 1
      },
      projectGroups: [],
      departments: [],
      tableData: [],
      statsData: [],
      moment,
      tableHeight: null
    }
  },
  mounted() {
    this.initTableHeight()
    // this.initData()
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.initTableHeight)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initTableHeight)
  },
  methods: {
    formatDate(date) {
      if (!date) return ''
      return this.moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已审核',
        2: '未采用'
      }
      return statusMap[status] || '未知'
    },
    getStatusColor(status) {
      const colorMap = {
        0: 'orange',
        1: 'green',
        2: 'red'
      }
      return colorMap[status] || 'default'
    },
    initTableHeight() {
      const clientHeight = document.documentElement.clientHeight
      this.tableHeight = clientHeight - 64 - 48 - 132 - 44
    },
    async initData() {
      await Promise.all([
        this.fetchProjectGroups(),
        this.fetchDepartments()
      ])
      this.fetchTableData()
      this.fetchStatsData()
    },
    async fetchProjectGroups() {
      try {
        const res = await apiProjectGroupList()
        if (res.code === 200) {
          this.projectGroups = res.data || []
          console.log('项目组列表:', this.projectGroups)
        }
      } catch (error) {
        console.error('获取项目组列表失败:', error)
        this.$message.error('获取项目组列表失败')
      }
    },
    async fetchDepartments() {
      try {
        const res = await apiDepartmentList()
        if (res.code === 200) {
          this.departments = res.data || []
          console.log('部门列表:', this.departments)
        }
      } catch (error) {
        console.error('获取部门列表失败:', error)
        this.$message.error('获取部门列表失败')
      }
    },
    async fetchTableData() {
      this.loading = true
      try {
        const params = this.getSearchParams()
        const res = await apiContributionGetStatsList(params)
        if (res.code === 200) {
          this.tableData = res.data || []
          console.log('统计数据:', this.tableData)
        } else {
          this.$message.error(res.message || '获取统计数据失败')
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      } finally {
        this.loading = false
      }
    },
    async fetchStatsData() {
      this.statsLoading = true
      try {
        const params = this.getSearchParams()
        const res = await apiPersonGetAllContributionStats(params)
        if (res.code === 200) {
          this.statsData = res.data || []
          console.log('个人统计数据:', this.statsData)
        } else {
          this.$message.error(res.message || '获取个人统计数据失败')
        }
      } catch (error) {
        console.error('获取个人统计数据失败:', error)
        this.$message.error('获取个人统计数据失败')
      } finally {
        this.statsLoading = false
      }
    },
    getSearchParams() {
      const params = {}
      const { dateRange, project_group_id, department_id, person_name, approved_status,has_platform_submit_date } = this.filterForm

      if (dateRange && dateRange.length === 2) {
        params.start_date = moment(dateRange[0]).format('YYYY-MM-DD')
        params.end_date = moment(dateRange[1]).format('YYYY-MM-DD')
      }

      if (project_group_id) {
        params.project_group_id = project_group_id
      }

      if (department_id) {
        params.department_id = department_id
      }

      if (person_name) {
        params.person_name = person_name
      }

      if (approved_status !== undefined) {
        params.approved_status = approved_status
      }

      if (has_platform_submit_date !== undefined) {
        params.has_platform_submit_date = has_platform_submit_date
      }

      return params
    },
    handleSearch() {
      this.fetchTableData()
      this.fetchStatsData()
    },
    handleReset() {
      this.filterForm = {
        dateRange: [],
        project_group_id: undefined,
        department_id: undefined,
        person_name: '',
        approved_status: undefined,
        has_platform_submit_date:1
      }
      this.fetchTableData()
      this.fetchStatsData()
    },
    exportDetail() {
      try {
        // 准备导出数据
        const exportData = this.tableData.map(item => ({
          'ID': item.contribution_id,
          '作品名': item.title,
          '作者1': item.author1_name ? `${item.author1_name} (${item.author1_department_name})` : '',
          '作者2': item.author2_name ? `${item.author2_name} (${item.author2_department_name})` : '',
          '作者3': item.author3_name ? `${item.author3_name} (${item.author3_department_name})` : '',
          '项目组': item.project_group_name,
          '审核状态': this.getStatusText(item.approved_status),
          '审核人': item.approved_person_name,
          '总分': item.score,
          '打分人': item.scoring_person_name,
          '作者1得分': item.author1_score,
          '作者2得分': item.author2_score,
          '作者3得分': item.author3_score,
          '额外得分': item.extra_score,
          '抖音点赞数': item.tiktok_likes,
          '视频号播放量': item.channels_views,
          '视频号点赞数': item.channels_likes,
          '提交时间': item.submission_date ? this.formatDate(item.submission_date) : '',
          '发布时间': item.platform_submit_date ? this.formatDate(item.platform_submit_date) : '',
          '备注': item.remarks
        }))

        // 创建工作簿
        const ws = XLSX.utils.json_to_sheet(exportData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '投稿明细')

        // 导出文件
        XLSX.writeFile(wb, '投稿明细.xlsx')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    },
    exportStats() {
      try {
        // 准备导出数据
        const exportData = this.statsData.map(item => ({
          '姓名': item.person_name,
          '部门': item.department_name,
          '作者1-投稿数': item.author1?.count || 0,
          '作者1-得分': item.author1?.score || 0,
          '作者2-投稿数': item.author2?.count || 0,
          '作者2-得分': item.author2?.score || 0,
          '作者3-投稿数': item.author3?.count || 0,
          '作者3-得分': item.author3?.score || 0,
          '总投稿数': item.total?.count || 0,
          '总得分': item.total?.score || 0
        }))

        // 创建工作簿
        const ws = XLSX.utils.json_to_sheet(exportData)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '个人统计')

        // 导出文件
        XLSX.writeFile(wb, '个人统计.xlsx')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.calculate-container {
  height: 100%;
  
  .search-area {
    padding: 24px 24px 16px 24px;
    background: #fff;
    border-radius: 4px;
  }
  
  .table-area {
    background: #fff;
    padding: 0 24px 16px;
    border-radius: 4px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 16px;

      .title {
        display: flex;
        align-items: center;
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);

        .icon {
          width: 4px;
          height: 16px;
          background-color: #1890ff;
          border-radius: 2px;
          margin-right: 8px;
        }
      }
    }
  }
}
</style>
